package fragment;

import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.Xml;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.FitCenter;
import com.example.mywood.AboutUsActivity;
import com.example.mywood.GoodsInfomationActivity;
import com.example.mywood.LoginActivity;
import com.example.mywood.MainActivity;
import com.example.mywood.R;
import com.example.mywood.SearchActivity;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.youth.banner.Banner;
import com.youth.banner.loader.ImageLoader;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xmlpull.v1.XmlPullParser;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import adapter.MainRecyclerViewAdapter;
import bean.ContentDataBean;
import bean.HomeGoodsBean;
import bean.ShaixuanallBean;
import myapp.MyApp;
import myview.CustomProgressDialog;
import myview.PullLoadMoreRecyclerView;
import myview.RatioImageView;
import myview.XCFlowLayout;
import util.DensityUtil;
import util.GlideUtils;
import util.MyLog;
import util.OrderEventMessage;
import util.RequestManager;
import util.saveImagUtil;
import util.utils;

import static com.facebook.FacebookSdk.getApplicationContext;

public class HomeFragment extends Fragment {

    private View view;
    private Context mcontext;
    private LinearLayout ll_search_wood;
    private LinearLayout ll_search;
    private RelativeLayout rl_search;
    private MyApp myapp;
    private String token;
    private int page = 1;
    private int pagesize = 20;
//    private List<HomeGoodsBean.DataBean.BannerBean.ZInfoBean.g> tembannerList = new ArrayList<>();
    private List<HomeGoodsBean.DataBean.ProductBean> temgoodsList = new ArrayList<>();
    private List<HomeGoodsBean.DataBean.ProductBean> goodsList = new ArrayList<>();
    private List<String> bannerlist = new ArrayList<>();
    private PullLoadMoreRecyclerView goodsRecycleView;
    private LinearLayoutManager layoutManager;
    private MainRecyclerViewAdapter adapter;
    private View bottomView;
    private View bannerView;
    private Banner banner;
    private LinearLayout loadLlay;
    private LinearLayout ll_home_shaixuan;
    private int width;
    private List<ShaixuanallBean.DataBean> temshaixuanallList = new ArrayList<>();//筛选多条件临时数据
    private PopupWindow mPopupWindow;
    private LayoutInflater mInflater;
    private int heightPixels;
    private View loadMoreShopView;
    private View notMoreShopView;
    private String apptype = "";
    private String textData;
    private SharedPreferences spuserInfo;
    private CustomProgressDialog customProgressDialog;
    private ContentDataBean.DataBean textContent;
    private WebView webview;
    private TextView tv_about;
    private TextView tv_more;
    private String contentwebview = "";
    private ImageView img_about;
    private String imageabout;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        MyLog.e("Activity:", this.getClass().getName().toString());
        view = inflater.inflate(R.layout.fragment_home, container, false);
        mcontext = getActivity();
        myapp = (MyApp) mcontext.getApplicationContext();
        spuserInfo = mcontext.getSharedPreferences("userInfo", Activity.MODE_PRIVATE);
        token = spuserInfo.getString("token", "");
        apptype = spuserInfo.getString("apptype", "0");
        textData = spuserInfo.getString("textData", "");
        mInflater = LayoutInflater.from(mcontext);
        EventBus.getDefault().register(this);
        customProgressDialog = new CustomProgressDialog(mcontext, "", R.style.CommProgressDialog);
        customProgressDialog.show();
        WindowManager.LayoutParams params = customProgressDialog.getWindow().getAttributes();
        params.alpha = 0.7f;//取值为0-1之间  0是全透明，1是不透明
        params.dimAmount=0f;   //取值为0-1之间  1是全黑
//		params.width = 180;//设置进度条的宽度
//		params.height = 180;//设置进度条的宽度
        customProgressDialog.getWindow().setAttributes(params);
        customProgressDialog.show();

        getScreenDen();
        initView();
        initTopView();
        initLin();
        getAboutData();
        getShaixuanData();
        return view;

    }

    @Subscribe
    public void onEventMainThread(OrderEventMessage event) {
        String message = event.getMessage();
        MyLog.e("message--new--order", message);
        if ("刷新数据".equals(message)) {
            page = 1;
            getAboutData();
        }

    }

    private void initView() {
        textContent = new Gson().fromJson(textData, new TypeToken<ContentDataBean.DataBean>() {}.getType());
        TextView tv_title = view.findViewById(R.id.tv_title);
        ll_search = view.findViewById(R.id.ll_search);
        rl_search = view.findViewById(R.id.rl_search);
        ll_search_wood = view.findViewById(R.id.ll_search_wood);
        goodsRecycleView = view.findViewById(R.id.rclv_goods);
//        goodsRecycleView.setLinearLayout();
        adapter = new MainRecyclerViewAdapter(temgoodsList, mcontext, myapp,width,textContent);
        setHeader(goodsRecycleView);
        goodsRecycleView.setAdapter(adapter);
        goodsRecycleView.setGridLayout2(2);
        goodsRecycleView.setRefreshing(true);
        layoutManager = (LinearLayoutManager) goodsRecycleView.getLayoutManager();
        GridLayoutManager gridLayoutManager = goodsRecycleView.getGridLayoutManager();
        goodsRecycleView.cancleAnimal();
        loadMoreShopView = View.inflate(mcontext, R.layout.item_moredata, null);
        notMoreShopView = View.inflate(mcontext, R.layout.item_nodata, null);

        if (textContent != null){
            tv_title.setText(textContent.getHomepage());
        }

        /*//通过isTitle的标志来判断是否是title
        gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
//                MyLog.e("show",position+"toshitringxxxxx888");
                if(position >=0 ){
                    return 2;
                }else {
                    return 1;
                }
            }
        });*/
//        goodsRecycleView.setGridLayout();

    }
    /**
     * 设置头部布局
     *
     * @param view
     */
    private void setHeader(PullLoadMoreRecyclerView view) {
        //轮播图
        bannerView = LayoutInflater.from(mcontext).inflate(R.layout.item_home_banner, view, false);
        adapter.setBannerView(bannerView);

        //底部加载更多
        bottomView = LayoutInflater.from(mcontext).inflate(R.layout.main_bottom, view, false);
        adapter.setBottomView(bottomView);
    }
    /**
     * 初始化头部控件
     */
    private void initTopView() {
        //轮播图
        banner = (Banner) bannerView.findViewById(R.id.banner);
        webview = bannerView.findViewById(R.id.webview);
        tv_about = bannerView.findViewById(R.id.tv_about);
        tv_more = bannerView.findViewById(R.id.tv_more);
        img_about = bannerView.findViewById(R.id.img_about);



        ll_home_shaixuan = (LinearLayout) bannerView.findViewById(R.id.ll_home_shaixuan);
        TextView tv_goods_list = (TextView) bannerView.findViewById(R.id.tv_goods_list);
        TextView tv_shaixuan = (TextView) bannerView.findViewById(R.id.tv_shaixuan);
        ContentDataBean.DataBean textContent = new Gson().fromJson(textData, new TypeToken<ContentDataBean.DataBean>() {}.getType());
        if (textContent != null){
            tv_goods_list.setText(textContent.getGoods_list());
            tv_shaixuan.setText(textContent.getShuaixuan());
            tv_more.setText(textContent.getView_more());
            tv_about.setText(textContent.getAbout_us());
        }

        //加载更多
        loadLlay = (LinearLayout) bottomView.findViewById(R.id.llay_load);
    }

    private void initLin() {
        tv_more.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(mcontext, AboutUsActivity.class);
                startActivity(intent);
            }
        });

        ll_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(mcontext, SearchActivity.class);
                intent.putExtra("activityType","");
                intent.putExtra("showroom","");
                startActivity(intent);
            }
        });
        goodsRecycleView.setOnPullLoadMoreListener(new PullLoadMoreRecyclerView.PullLoadMoreListener() {
            @Override
            public void onRefresh() {
                /*clickids.clear();
                for (int m = 0;m<tempClickids.size();m++){
                    clickids.add(tempClickids.get(m));
                }*/
                //          {"attr_58": "1,56,23,45","attr_58": "1,56,23,45"}
                String paramJson = "{";
                for (int m = 0;m<temshaixuanallList.size();m++){
                    //循环遍历每一个大分类的id
                    int id = temshaixuanallList.get(m).getId();
                    StringBuffer sbf = new StringBuffer();
                    sbf.append("\"");
                    sbf.append(id);
                    sbf.append("\":\"");
                    for (int t = 0; t < clickids.size(); t++) {
                        String s = clickids.get(t);
                        String[] split = s.split("=");
                        if (split[1].equals(id+"")){
                            sbf.append(split[0] + ",");
                        }
                    }
                    boolean isadd = false;
                    if (sbf.toString().contains(",")){
                        isadd = true;
                    }
                    String substring = sbf.substring(0, sbf.length() - 1);
                    substring = substring+"\",";
                    if (isadd){
                        paramJson = paramJson+substring;
                    }
                }
                paramJson = paramJson.substring(0,paramJson.length()-1);
                paramJson = paramJson+"}";
                MyLog.e("组合id的json",paramJson+"    JSon格式");
                page = 1;
                if (clickids.size() == 0){
                    paramJson = "";
                }
                getData(paramJson);
//                goodsRecycleView.setPullLoadMoreCompleted();
            }

            @Override
            public void onLoadMore() {
                /*clickids.clear();
                for (int m = 0;m<tempClickids.size();m++){
                    clickids.add(tempClickids.get(m));
                }*/
                //          {"attr_58": "1,56,23,45","attr_58": "1,56,23,45"}

                if (temgoodsList.size() != 0){


                customProgressDialog.show();
                String paramJson = "{";
                for (int m = 0;m<temshaixuanallList.size();m++){
                    //循环遍历每一个大分类的id
                    int id = temshaixuanallList.get(m).getId();
                    StringBuffer sbf = new StringBuffer();
                    sbf.append("\"");
                    sbf.append(id);
                    sbf.append("\":\"");
                    for (int t = 0; t < clickids.size(); t++) {
                        String s = clickids.get(t);
                        String[] split = s.split("=");
                        if (split[1].equals(id+"")){
                            sbf.append(split[0] + ",");
                        }
                    }
                    boolean isadd = false;
                    if (sbf.toString().contains(",")){
                        isadd = true;
                    }
                    String substring = sbf.substring(0, sbf.length() - 1);
                    substring = substring+"\",";
                    if (isadd){
                        paramJson = paramJson+substring;
                    }
                }
                paramJson = paramJson.substring(0,paramJson.length()-1);
                paramJson = paramJson+"}";
                    MyLog.e("组合id的json",paramJson+"    JSon格式");
                page++;
                if (clickids.size() == 0){
                    paramJson = "";
                }
                getData(paramJson);
                }else{
                    goodsRecycleView.setPullLoadMoreCompleted();
                }
            }

            @Override
            public void onScrollChanged(int heightTotal) {

            }

            @Override
            public void onScrollState(int type) {

            }
        });
        //店铺列表点击事件
        adapter.setOnItemClickListener(new MainRecyclerViewAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                MyLog.e("条目点击事件",position+"    item");
                int id = goodsList.get(position).getId();
                Intent intent = new Intent(mcontext, GoodsInfomationActivity.class);
                intent.putExtra("goodsid",id+"");
                startActivity(intent);
            }
        });
        ll_home_shaixuan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (utils.isFastDoubleClick()){
                    return;
                }

                if (temshaixuanallList.size() == 0){
                    Toast.makeText(mcontext,textContent.getPlease_retry(),Toast.LENGTH_LONG).show();
                    getShaixuanData();
                }else{
                    initallbyWindow();
                }
            }
        });
    }
    private void getAboutData() {
        String url = myapp.getWebConfig() + "/api/index/home_about";
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("token", token);
        paramsMap.put("is_material", apptype);
        RequestManager.getInstance(mcontext).requestAsyn(url, RequestManager.TYPE_POST_FORM, paramsMap, new RequestManager.ReqCallBack() {
            @Override
            public void onReqSuccess(Object result) {
                MyLog.e("code--result", result.toString());
                Message msg = new Message();
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    if (jsonObject.getString("code").equals("0")) {
//                        MyLog.e("111111111111111","351行"+msg.obj.toString());
                        msg.obj = jsonObject.getString("msg");
                        msg.arg1 = 0;
                        handler.sendMessage(msg);
                        return;
                    }


                    JSONObject data = jsonObject.getJSONObject("data");
                    contentwebview = data.getString("content");
                    imageabout = data.getString("image");



                    msg.arg1 = 4;
                    handler.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    msg.arg1 = 1;
                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                MyLog.e("result-selected_list", errorMsg);
                if (errorMsg.equals("未登录")){
                    Message msg = new Message();
                    msg.arg1 = 11;
                    handler.sendMessage(msg);
                }else{
                    Message msg = new Message();
                    msg.arg1 = 12;
                    handler.sendMessage(msg);
                }
            }
        });
    }
    private void getData(String ids) {
        temgoodsList.clear();
        bannerlist.clear();


        MyLog.e("code--result", token+"   token值   "+ids);
        String url = myapp.getWebConfig() + "/api/index/selected_list";
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("token", token);
        paramsMap.put("search", ids);
        paramsMap.put("page", page+"");
        paramsMap.put("size", pagesize+"");
        paramsMap.put("is_material", apptype);
        RequestManager.getInstance(mcontext).requestAsyn(url, RequestManager.TYPE_POST_FORM, paramsMap, new RequestManager.ReqCallBack() {
            @Override
            public void onReqSuccess(Object result) {
                MyLog.e("code--result", result.toString());
                Message msg = new Message();
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    if (jsonObject.getString("code").equals("0")) {
//                        MyLog.e("111111111111111","351行"+msg.obj.toString());
                        msg.obj = jsonObject.getString("msg");
                        msg.arg1 = 0;
                        handler.sendMessage(msg);
                        return;
                    }


                    JSONObject data = jsonObject.getJSONObject("data");
                    JSONArray product = data.getJSONArray("product");
                    JSONObject banner = data.getJSONObject("banner");
                    JSONObject z_info = banner.getJSONObject("z_info");
                    JSONArray bannerlistarray = z_info.getJSONArray("banner");
                    for (int i = 0;i<bannerlistarray.length();i++){
                        bannerlist.add(bannerlistarray.getString(i));
                    }

//                    tembannerList = new Gson().fromJson(bannerlist.toString(), new TypeToken<List<HomeGoodsBean.DataBean.BannerBean.ZInfoBean>>() {
//                    }.getType());
                    temgoodsList = new Gson().fromJson(product.toString(), new TypeToken<List<HomeGoodsBean.DataBean.ProductBean>>() {
                    }.getType());


                    msg.arg1 = 3;
                    handler.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    msg.arg1 = 1;
                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                MyLog.e("result-selected_list", errorMsg);
                if (errorMsg.equals("未登录")){
                    Message msg = new Message();
                    msg.arg1 = 11;
                    handler.sendMessage(msg);
                }else{
                    Message msg = new Message();
                    msg.arg1 = 12;
                    handler.sendMessage(msg);
                }
            }
        });
    }
    /**
     * 筛选目录的内容
     */
    private void getShaixuanData() {
        temshaixuanallList.clear();
        String url = myapp.getWebConfig() + "/api/index/search_condition";
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("token", token);
        paramsMap.put("is_material", apptype);
        RequestManager.getInstance(mcontext).requestAsyn(url, RequestManager.TYPE_POST_FORM, paramsMap, new RequestManager.ReqCallBack() {
            @Override
            public void onReqSuccess(Object result) {
                MyLog.e("code--result", result.toString());
                Message msg = new Message();
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    if (jsonObject.getString("code").equals("0")) {
//                        MyLog.e("111111111111111","411行"+msg.obj.toString());
                        msg.obj = jsonObject.getString("msg");
                        msg.arg1 = 0;
                        handler.sendMessage(msg);
                        return;
                    }
                    JSONArray data = jsonObject.getJSONArray("data");
                    temshaixuanallList = new Gson().fromJson(data.toString(), new TypeToken<List<ShaixuanallBean.DataBean>>() {
                    }.getType());


                    msg.arg1 = 2;
                    handler.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    msg.arg1 = 1;
                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                MyLog.e("result-search_condition", errorMsg);
                if (errorMsg.equals("未登录")){
                    Message msg = new Message();
                    msg.arg1 = 11;
                    handler.sendMessage(msg);
                }
            }
        });
    }

    public Handler handler = new Handler(){

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.arg1){
                case 0:
                    if (customProgressDialog != null){
                        if (customProgressDialog.isShowing()){
                            customProgressDialog.dismiss();
                        }
                    }
                    String str = msg.obj.toString();
                    Toast.makeText(mcontext,str,Toast.LENGTH_LONG).show();
                    break;
                case 1:
                    if (customProgressDialog != null){
                        if (customProgressDialog.isShowing()){
                            customProgressDialog.dismiss();
                        }
                    }
                    Toast.makeText(mcontext,textContent.getNet_error(),Toast.LENGTH_LONG).show();
                    break;
                case 2:
//                    initallbyWindow();
                    break;
                case 3:
                    if (customProgressDialog != null){
                        if (customProgressDialog.isShowing()){
                            customProgressDialog.dismiss();
                        }
                    }
                    if (page == 1){
                        adapter.notifyDataSetChanged();
                    }
                    if (mPopupWindow != null) {
                        mPopupWindow.dismiss();
                    }
                    goodsRecycleView.setPullLoadMoreCompleted();
                    banner.setVisibility(View.VISIBLE);
                    banner.setImageLoader(new GlideImageMidlllunboLoader());
                    banner.setImages(bannerlist);
                    banner.start();

//                    adapter.setDatas(temgoodsList);




                    if (page == 1) {
                        goodsList.clear();
                    }
                    goodsList.addAll(temgoodsList);
                    adapter.setDatas(goodsList);
                    loadLlay.removeAllViews();
                    if (temgoodsList.size() == 20) {
//                        loadLlay.addView(loadMoreShopView);
                        MyLog.e("11111111", "    高度");
                    } else {
//                        loadLlay.addView(notMoreShopView);
                    }
                    if (goodsList.size() == 0){
                        Toast.makeText(mcontext,textContent.getNodata(),Toast.LENGTH_LONG).show();
                    }

                    break;
                case 4:
                    GlideUtils.loadRoundCircleImage(getApplicationContext(), imageabout + "", img_about);

                    webview.getSettings().setDefaultTextEncodingName("UTF-8");
                    webview.loadDataWithBaseURL(null, contentwebview+"<style> img{max-width:100%;max-height:100%} </style>", "text/html", "utf-8", null);
                    webview.setWebViewClient(new WebViewClient());
                    getData("");
                    break;
                case 11:
                    if (!islogin){
                        islogin = true;
                        spuserInfo.edit().putString("token", "").commit();
                        Intent intent = new Intent(mcontext, LoginActivity.class);
                        mcontext.startActivity(intent);
                        myapp.destoryActivity("主页面");
                    }
                    break;
                case 12:
                    if (customProgressDialog != null){
                        if (customProgressDialog.isShowing()){
                            customProgressDialog.dismiss();
                        }
                    }
                    goodsRecycleView.setPullLoadMoreCompleted();
                    break;
            }
        }
    };

    private boolean islogin = false;
    public class GlideImageMidlllunboLoader extends ImageLoader {

        @Override
        public ImageView createImageView(Context context) {


            XmlPullParser parser = getApplicationContext().getResources().getXml(R.xml.layout_ratioimageview);
            AttributeSet attributes = Xml.asAttributeSet(parser);

            ImageView imageView = new RatioImageView(context, attributes);

            return imageView;
        }

        @Override
        public void displayImage(final Context context, final Object path, ImageView imageView) {
//            Glide.with(getApplicationContext()).load(path).transform(new FitCenter(context), new GlideRoundTransform(context)).into(imageView);
            if ("".equals(path)){
                imageView.setImageResource(R.mipmap.icon_wood_error);
            }else {
                GlideUtils.loadRoundCircleImage(getApplicationContext(), path + "", imageView);
            }
            final String imgurl = path+"";
            imageView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View view) {
                    saveImagUtil.showDiaLog(context,imgurl,textContent);
                    return true;
                }
            });
        }
    }
    /**
     * 获取屏幕宽度
     */
    private void getScreenDen() {
//        dm = new DisplayMetrics();
//        heightPixels = dm.heightPixels;
//        getWindowManager().getDefaultDisplay().getMetrics(dm);

        WindowManager manager = getActivity().getWindowManager();
        DisplayMetrics dm = new DisplayMetrics();
        manager.getDefaultDisplay().getMetrics(dm);
        //以要素为单位
        width = dm.widthPixels;
        heightPixels = dm.heightPixels;
        MyLog.e("获取屏幕高度", heightPixels + "    高度   "+width);
    }

    private List<String> clickids = new ArrayList<>();
    List<XCFlowLayout> viewssss = new ArrayList<>();
    List<String> tempClickids = new ArrayList<>();
    /**
     * 弹出多筛选框
     */
    private void initallbyWindow() {
        viewssss.clear();
        tempClickids.clear();
        for (int m = 0;m<clickids.size();m++){
            tempClickids.add(clickids.get(m));
        }
        clickids.clear();

        LayoutInflater layoutInflater = LayoutInflater.from(mcontext);
        View popupWindow = layoutInflater.inflate(R.layout.popup_allshaixuan, null);
        View viewById = popupWindow.findViewById(R.id.view_zhezhao);
        ImageView img_back_pop = popupWindow.findViewById(R.id.img_back_pop);
        TextView tv_title_name = popupWindow.findViewById(R.id.tv_title_name);
        img_back_pop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mPopupWindow.dismiss();
            }
        });
        viewById.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPopupWindow.dismiss();
            }
        });
        TextView tv_clear = popupWindow.findViewById(R.id.tv_clear);
        final LinearLayout ll_content = popupWindow.findViewById(R.id.ll_content);
        TextView tv_sure = popupWindow.findViewById(R.id.tv_sure);
        ContentDataBean.DataBean textContent = new Gson().fromJson(textData, new TypeToken<ContentDataBean.DataBean>() {}.getType());
        if (textContent != null){
            tv_clear.setText(textContent.getResetting());
            tv_sure.setText(textContent.getDefine());
        }

        tv_clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                clickids.clear();
                tempClickids.clear();
                for (int m = 0; m < viewssss.size(); m++) {
                    XCFlowLayout viewone = viewssss.get(m);
                    int xccount = viewone.getChildCount();
                    for (int n = 0; n < xccount; n++) {
                        TextView childAt = (TextView) viewone.getChildAt(n);
                        childAt.setBackgroundResource(R.drawable.kong_bg);
                        childAt.setTextColor(getResources().getColor(R.color.color333));
                    }
                }


            }
        });
        tv_sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                customProgressDialog.show();
                clickids.clear();
                for (int m = 0;m<tempClickids.size();m++){
                    clickids.add(tempClickids.get(m));
                }
                //          {"attr_58": "1,56,23,45","attr_58": "1,56,23,45"}
                String paramJson = "{";
                for (int m = 0;m<temshaixuanallList.size();m++){
                    //循环遍历每一个大分类的id
                    int id = temshaixuanallList.get(m).getId();
                    StringBuffer sbf = new StringBuffer();
                    sbf.append("\"");
                    sbf.append(id);
                    sbf.append("\":\"");
                    for (int t = 0; t < clickids.size(); t++) {
                        String s = clickids.get(t);
                        String[] split = s.split("=");
                        if (split[1].equals(id+"")){
                            sbf.append(split[0] + ",");
                        }
                    }
                    boolean isadd = false;
                    if (sbf.toString().contains(",")){
                        isadd = true;
                    }
                    String substring = sbf.substring(0, sbf.length() - 1);
                    substring = substring+"\",";
                    if (isadd){
                        paramJson = paramJson+substring;
                    }
                }
                paramJson = paramJson.substring(0,paramJson.length()-1);
                if (!"".equals(paramJson)){
                    paramJson = paramJson+"}";
                }
                MyLog.e("组合id的json",paramJson+"    JSon格式");


                page = 1;
                getData(paramJson);
            }
        });

        ll_content.removeAllViews();
        for (int i = 0; i < temshaixuanallList.size(); i++) {
            View view = View.inflate(mcontext, R.layout.item_shaixuanall, null);
            TextView tv_name = view.findViewById(R.id.tv_name);
            tv_name.setText(temshaixuanallList.get(i).getAttr_name());


            List<ShaixuanallBean.DataBean.AttrListBean> attr_list = temshaixuanallList.get(i).getAttr_list();
            final XCFlowLayout flowlayout = view.findViewById(R.id.flowlayout);
            for (int m = 0; m < attr_list.size(); m++) {
                TextView tvview = (TextView) mInflater.inflate(
                        R.layout.item_shuaixuanitem, flowlayout, false);
                tvview.setText(attr_list.get(m).getAttr_value());
                tvview.setTag(attr_list.get(m).getId() + "=" + attr_list.get(m).getKind_id());
                flowlayout.addView(tvview, m);

                for (int k = 0;k<tempClickids.size();k++){
                    String s = tempClickids.get(k);
                    String[] split = s.split("=");
                    String sonid = attr_list.get(m).getId()+"";
                    String fuid = attr_list.get(m).getKind_id()+"";
                    if (sonid.equals(split[0]) && fuid.equals(split[1])){
                        tvview.setBackgroundResource(R.drawable.orange_kong_bg);
                        tvview.setTextColor(getResources().getColor(R.color.colordorange));
                        break;
                    }
                }

                viewssss.add(flowlayout);
                flowlayout.getChildAt(m).setOnClickListener(
                        new View.OnClickListener() {

                            @Override
                            public void onClick(View v) {
                                int childCount = flowlayout.getChildCount();


                                String tab = ((TextView) v).getText()
                                        .toString().trim();
                                String tag = (String) v.getTag();

                                String[] split = tag.split("=");
                                boolean issame = false;
                                //遍历id和父id，判断当前被点击的之前有没有被点击过
                                for (int a = 0; a < tempClickids.size(); a++) {
                                    String s = tempClickids.get(a);
                                    if (s.contains(split[1])) {
                                        //父id一样，都给移除掉
                                        if (s.contains(split[0])){
                                            tempClickids.remove(a);
                                            //说明父id一样，子id一样，就是说是同一个标签
                                            issame = true;
                                        }

                                    }


                                }
                                if (issame){
                                    //如果是同一个，就把当前标签变成没选中状态
                                    v.setBackgroundResource(R.drawable.kong_bg);
                                    ((TextView) v).setTextColor(getResources().getColor(R.color.color333));
                                }

                                if (!issame){
                                    tempClickids.add(tag);
                                    MyLog.e("选中条目", tab + "   选中条目内容     " + tag);
                                    v.setBackgroundResource(R.drawable.orange_kong_bg);
                                    ((TextView) v).setTextColor(getResources().getColor(R.color.colordorange));
                                }
                            }
                        });
            }


            ll_content.addView(view);


        }


        int mScreenWidth = getActivity().getWindowManager().getDefaultDisplay().getWidth();
        mPopupWindow = new PopupWindow(popupWindow, ActionBar.LayoutParams.FILL_PARENT,
                ActionBar.LayoutParams.FILL_PARENT);
        mScreenWidth = getActivity().getWindowManager().getDefaultDisplay().getHeight();
        int mPopupWindowWidth = mPopupWindow.getWidth();
        int mPopupWindowHeight = mPopupWindow.getHeight();
        // 需要设置一下此参数，点击外边可消失
        mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
        mPopupWindow.setOutsideTouchable(true);
        mPopupWindow.setTouchable(true);
        mPopupWindow.setFocusable(true); // pop 显示时， 不让外部 view 响应点击事件


        if (Build.VERSION.SDK_INT >= 24) { // Android 7.x中,PopupWindow高度为match_parent时,会出现兼容性问题,需要处理兼容性
            int offsetY = DensityUtil.dip2px(mcontext, 24);
            if (Build.VERSION.SDK_INT >= 25) { // Android 7.1中，PopupWindow高度为 match_parent 时，会占据整个屏幕
                //故而需要在 Android 7.1上再做特殊处理
                int screenHeight = heightPixels; // 获取屏幕高度
//                int screenHeight = DisplayUtil.getScreenHeight(MainActivity.this); // 获取屏幕高度
                mPopupWindow.setHeight(screenHeight - offsetY); // 重新设置 PopupWindow 的高度
            }
            mPopupWindow.showAtLocation(ll_home_shaixuan, Gravity.NO_GRAVITY, 0, offsetY);
        } else {
//            mPopupWindow.showAsDropDown(rl_search);
            int offsetY = DensityUtil.dip2px(mcontext, 24);
//            if (Build.VERSION.SDK_INT >= 25) { // Android 7.1中，PopupWindow高度为 match_parent 时，会占据整个屏幕
                //故而需要在 Android 7.1上再做特殊处理
                int screenHeight = heightPixels; // 获取屏幕高度
//                int screenHeight = DisplayUtil.getScreenHeight(MainActivity.this); // 获取屏幕高度
                mPopupWindow.setHeight(screenHeight - offsetY); // 重新设置 PopupWindow 的高度
//            }
            mPopupWindow.showAtLocation(ll_home_shaixuan, Gravity.NO_GRAVITY, 0, offsetY);
        }

        mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                clickids.clear();
                for (int m = 0;m<tempClickids.size();m++){
                    clickids.add(tempClickids.get(m));
                }
                tempClickids.clear();
                MyLog.e("弹窗消失", "00000000000000");
//                tv_caizhi.setTextColor(getResources().getColor(R.color.color333));
//                tv_color.setTextColor(getResources().getColor(R.color.color333));
//                tv_function.setTextColor(getResources().getColor(R.color.color333));
//                tv_area.setTextColor(getResources().getColor(R.color.color333));
//                img_caizhi.setImageResource(R.mipmap.icon_down_gray);
//                img_color.setImageResource(R.mipmap.icon_down_gray);
//                img_function.setImageResource(R.mipmap.icon_down_gray);
//                img_area.setImageResource(R.mipmap.icon_down_gray);
            }
        });

    }
    @Override
    public void onResume() {
        super.onResume();
        MyLog.e("首页","onResume");
    }
    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        MyLog.e("首页","onHiddenChanged     "+hidden);
        if (!hidden){
//            goodsRecycleView.scrollToTop();
        }
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
